package controller.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.GeneralUtil;

import model.business.product.ProductState;
import model.dao.JPAHiberDAOFactory;
import model.dao.entity.BrandDAO;
import model.dao.entity.ProductDAO;
import model.entity.product.ActionToy;
import model.entity.product.Computer;
import model.entity.product.Phone;
import model.entity.product.Product;
import model.entity.product.StaticToy;
import model.entity.product.TV;

import com.google.gson.Gson;

public class ProductContr extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProductDAO productDAO;
	private Gson gson;
	private Map<String, Class<?>> currentFieldMap;
	private int id;
       
    public ProductContr() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String commnad = request.getParameter("command");
		if (commnad != null){
			productDAO = (ProductDAO) JPAHiberDAOFactory.getInstance().getProductDAO();
			gson = new Gson();
			
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			
			Class<? extends Product> c = findClass(commnad);
			List<? extends Product> listProduct = productDAO.selectAllBySubClass(c);
			
			for (Product product : listProduct) {
				out.print(product.toString());
			}
			
			String objectToTransfer = gson.toJson(listProduct);
			out.print(objectToTransfer);
		}
	}

	private Class<? extends Product> findClass(String commnad) {
		switch (commnad) {
		case "Phone":
			this.currentFieldMap = Phone.fieldMap();
			return Phone.class;
		case "TV":
			this.currentFieldMap = TV.fieldMap();
			return TV.class;
		case "Computer":
			this.currentFieldMap = Computer.fieldMap();
			return Computer.class;
		case "StaticToy":
			this.currentFieldMap = StaticToy.fieldMap();
			return StaticToy.class;
		case "ActionToy":
			this.currentFieldMap = ActionToy.fieldMap();
			return ActionToy.class;
		default:
			return null;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String commnad = request.getParameter("command");
		String type = request.getParameter("type");
		String json = request.getParameter("json");
		
		if (commnad != null){
			productDAO = (ProductDAO) JPAHiberDAOFactory.getInstance().getProductDAO();
			gson = new Gson();

			Class<? extends Product> c = findClass(type);
			//Lay du lieu json neu co
			if(json != null){
				json = GeneralUtil.getJsonStringSimp(request);
				Product product = gson.fromJson(json, c);
				id = product.getId();
			} else {
				id = Integer.parseInt(request.getParameter("id"));
				normalRequest(request, commnad, c);
			}
			
			//Cac ham xu ly chi can id
			if (commnad.equals("delete")){
				productDAO.deleteByID(id);
			}
		}
	}

	private void normalRequest(HttpServletRequest request, String commnad, Class<? extends Product> c) {
		
		//Xy ly da so du lieu
		Map<String, Object> valueMap = GeneralUtil.processValueMap(request,this.currentFieldMap);
		if(GeneralUtil.checkNotNullField(valueMap,ProductDAO.notNullFields))
		{
			//Ham xy ly 2 bien du lieu lon con lai (sau ham process co gia tri -1)
			//Brand
			BrandDAO brandDAO = new BrandDAO();
			valueMap.put("brand", brandDAO.findReference(Integer.parseInt(request.getParameter("brand"))));
			
			//State
			valueMap.put("state", ProductState.createState(Integer.parseInt(request.getParameter("state"))));
			
			
			//Ham xu ly viet doc lap voi json
			if (commnad.equals("create")) {
				Product instance = null;
				 try {
					instance = c.getConstructor().newInstance();
				} catch (Exception e) {
					e.printStackTrace();
				}
				instance.insertData(valueMap);
				productDAO.persist(instance);
			}
			if (commnad.equals("update")){
				Product product = productDAO.findReference(id);
				product.insertData(valueMap);
				productDAO.persist(product);
			}	
		}
	}
	
	public static void main(String[] args) {
		ProductDAO productDAOT = (ProductDAO) JPAHiberDAOFactory.getInstance().getProductDAO();
		
//		List<Toy> listToy = productDAOT.selectAllBySubClass(Toy.class);
		List<Phone> listPhone = productDAOT.selectAllBySubClass(Phone.class);
		for (Phone toy : listPhone) {
			System.out.println(toy);
		}
		for (Entry<String, Class<?>> entry : Phone.fieldMap().entrySet()) {
			System.out.println(entry.getKey()+": "+entry.getValue());
		}
		
	}

}
